import httpx
import json
from fastapi import APIRouter, Query, Header, HTTPException, Request
from fastapi.responses import JSONResponse
from schemas.response import ResSuccess
from common.logger import logger

auth_router = APIRouter()


@auth_router.post("/login", summary="统一认证登录", description="统一认证登录")
async def get_sso_token(
    request: Request, 
    code: str = Query(..., description="必须传入code")
    ) -> JSONResponse:
    params = {
        'client_id': '1132719996372254720',
        'client_secret': 'avt0MTgwNjIwMjUxNDI1NTc2ODYZn4',
        'grant_type':'authorization_code',
        'redirect_uri':'http://172.16.119.110:5666/auth/sso',
        'code':code,
        'online':'one'
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }

    response = httpx.post(
        "http://192.168.24.132:8080/authz/oauth/v20/token",
        params=params,
        headers=headers
    )

    logger.info(response.text)
    if 'access_token' in response.text :
        return ResSuccess(data=response.json(), msg="登录成功")
    else:
        return ResSuccess(data=None, msg="登录失败")
    

@auth_router.get("/me", summary="获取用户信息", description="获取用户信息")
async def get_sso_userinfo(
    request: Request, 
    authorization: str = Header(..., description="必须传入Authorization头",
    alias="Authorization")
    ) -> JSONResponse:
    # 验证Authorization头格式
    if not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail="无效的认证格式，请使用Bearer token",
            headers={"WWW-Authenticate": "Bearer"}
        )

    # 提取token部分
    access_token = authorization[7:].strip()
    logger.info(access_token)
    if not access_token:
        raise HTTPException(
            status_code=401,
            detail="Token不能为空",
            headers={"WWW-Authenticate": "Bearer"}
        )
    response = httpx.post("http://192.168.24.132:8080/api/oauth/v20/me?access_token="+access_token)
    print(response)

    datas = response.json()
    roles = ["user"]
    datas["roles"] = roles
    logger.info(datas)
    if 'username' in response.text:
        try:
            redis = request.app.state.redis
            await redis.set(access_token, json.dumps(datas, ensure_ascii=False), ex=7200)
        except Exception as e:
            logger.error(f"向Redis存数据失败: {str(e)}", exc_info=True)
        return ResSuccess(data=datas, msg="获取成功")
    else:
        return ResSuccess(data=None, msg="获取失败")
    


@auth_router.get("/permiscodes", summary="获取权限编码", description="获取权限编码")
async def get_sso_user_permiscodes(request: Request,
        authorization: str = Header(..., description="必须传入Authorization头", 
        alias="Authorization")
) -> JSONResponse:
    if not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail="无效的认证格式，请使用Bearer token",
            headers={"WWW-Authenticate": "Bearer"}
        )

    # 提取token部分
    access_token = authorization[7:].strip()
    logger.info(access_token)
    if not access_token:
        raise HTTPException(
            status_code=401,
            detail="Token不能为空",
            headers={"WWW-Authenticate": "Bearer"}
        )
    datas = ["AC_1000100","AC_100110"]
    return ResSuccess(data=datas, msg="获取成功")